﻿using System;
using System.IO;
using System.Collections.Generic;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using GPC_Overlay;

namespace GISWebRole
{
    public partial class Upload : System.Web.UI.Page
    {
        BlobHelper _blobClient;
        internal const int BLOCK_SIZE = 4000000;//Each block can be 4 MB max in size

        protected void Page_Load(object sender, EventArgs e)
        {
            string connectionString = RoleEnvironment.GetConfigurationSettingValue("DataConnectionString");

            try
            {
                _blobClient = new BlobHelper(connectionString);
            }
            catch (Exception ex)
            {
                Trace.Write(ex.Message);
            }
        }

        protected void bntUploadClick(object sender, EventArgs e)
        {
            string connectionString = RoleEnvironment.GetConfigurationSettingValue("DataConnectionString");
            if (this.upldMapFile.HasFile)
            {
                var filename = upldMapFile.FileName;
                if (!_blobClient.CreateContainer(DataConstants.MAP_CONTAINER_BLOB))
                {
                    System.Diagnostics.Trace.WriteLine("Error creating Blob Container");
                }
               
                int id = 0;
                byte[] Data = new byte[BLOCK_SIZE];
                var streamTemp = upldMapFile.FileContent;
                int numBlocks = (int) Math.Ceiling((decimal)streamTemp.Length/BLOCK_SIZE);
                string[] blockIds = new string[numBlocks];

                using (var stream = upldMapFile.FileContent)
                {
                    while (stream.Length > stream.Position)
                    {
                        int toread = Math.Min((int)(stream.Length - stream.Position), BLOCK_SIZE);
                        stream.Read(Data, 0, toread);
                        while (!_blobClient.PutBlock(DataConstants.MAP_CONTAINER_BLOB, filename, id, blockIds, Data, toread))
                        {
                         System.Diagnostics.Trace.WriteLine("I am trying again to upload the last block as it failed the last time.");
                        }
                        id++;
                    }
                    BlobHelper.PutBlockList(connectionString, DataConstants.MAP_CONTAINER_BLOB,filename,blockIds);
                }
            }            
        }
    }
}
